<template>
  <div>
    <el-table
      :data="tableData"
      style="width: 100%"
      height="400"
      ref="mainTable"
    >
      <el-table-column label="人员">
        <template slot-scope="scope">
                    <el-button
            plain
            :type="isInterested(scope.row.name)?'danger':'info'"
            size="small"
            style="width:5em;padding:6px 0">{{ scope.row.name }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="纠违次数">
        <template slot-scope="scope">
          <el-button
            plain
            :type="scope.row.rectify > 0 ? 'warning' : 'primary'"
            size="small"
            style="width:4em;padding:6px 0"
            @click="
              $emit('stroke', { client: scope.row.name, type: 'rectify' })
            "
            >{{ scope.row.rectify }}次</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="检查数量">
        <template slot-scope="scope">
          <el-button
            plain
            :type="
              scope.row.inspect == 0
                ? 'warning'
                : scope.row.inspectNG > 0
                ? 'danger'
                : 'primary'
            "
            size="small"
            style="width:5em;padding:6px 0"
            @click="
              $emit('stroke', { client: scope.row.name, type: 'inspect' })
            "
            >{{ scope.row.inspect - scope.row.inspectNG }}/{{
              scope.row.inspect
            }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="检查评分">
        <template slot-scope="scope">
          <el-button
            plain
            :type="
              +scope.row.inspect < 4
                ? +scope.row.inspect < 3
                  ? 'danger'
                  : 'warning'
                : 'primary'
            "
            size="small"
            style="width:4em;padding:6px 0"
            @click="
              $emit('stroke', {
                client: scope.row.name,
                type: 'inspectSummary',
              })
            "
            >{{ scope.row.inspectAvg }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getDateRange } from "@/utils/date.js";

export default {
  computed: {
    storedClients() {
      return this.$store.state.summary.attention.clientSelected;
    },
    storedRange() {
      return this.$store.state.summary.attention.rangeSelected;
    },
    source() {
      return this.$store.getters.summarySource;
    },
    inspect() {
      return this.$store.state.summary.inspectSource;
    },
    timeRange() {
      return this.getDateRange({ type: this.range });
    },
    clientNames() {
      let arr = [];
      for (let i = 0; i < this.clients.length; i++) {
        arr.push(this.clients[i][2]);
      }
      return arr;
    },
  },
  data() {
    return {
      lastTime: "",
      tableData: [],
      multipleSelection: [],
      updateID: 0,
      clients: [],
      range: {},
      fetchedRectifyData: [],
      fetchedInspectData: [],
    };
  },
  methods: {
    getDateRange,
    fetchData() {
      //degub info
      this.fetchedRectifyData = [];
      this.fetchedInspectData = [];
      // this.lastTime = new Date().toLocaleString();
      if (!this.clientNames) return [];
      let tableData = [];
      for (
        let clientIdx = 0;
        clientIdx < this.clientNames.length;
        clientIdx++
      ) {
        let cell = {
          name: this.clientNames[clientIdx],
          rectify: 0,
          inspect: 0,
          inspectNG: 0,
          inspectVal: 0,
          inspectAvg: 0,
          count: 0,
          countNG: 0,
        };
        // console.log("fetchData");
        // console.log(this.timeRange);
        //rectify
        for (
          let rectifyIdx = 0;
          rectifyIdx < this.source.length;
          rectifyIdx++
        ) {
          if (this.source[rectifyIdx].clientName == cell.name) {
            let time = new Date(
              this.source[rectifyIdx].eventTime.replace(/-/g, "/")
            ).getTime();
            if (
              time >= this.timeRange.min.getTime() &&
              time <= this.timeRange.max.getTime()
            ) {
              //debug info
              this.fetchedRectifyData.push(this.source[rectifyIdx]);
              cell.rectify++;
              cell.countNG++;
              cell.count++;
            }
          }
        }
        //inspect
        for (
          let inspectIdx = 0;
          inspectIdx < this.inspect.length;
          inspectIdx++
        ) {
          if (this.inspect[inspectIdx].clientName == cell.name) {
            let begin = new Date(
              this.inspect[inspectIdx].begin.replace(/-/g, "/")
            );
            let time = new Date(
              this.inspect[inspectIdx].time.replace(/-/g, "/")
            );
            if (
              time.getTime() >= this.timeRange.min.getTime() ||
              begin.getTime() <= this.timeRange.max.getTime()
            ) {
              //debug info
              this.fetchedInspectData.push(this.inspect[inspectIdx]);
              cell.count++;
              cell.inspectVal += +this.inspect[inspectIdx].value;
              cell.inspect++;
              if (this.inspect[inspectIdx].value < 3) {
                cell.inspectNG++;
                cell.countNG++;
              }
            }
          }
          if (inspectIdx === this.inspect.length - 1) {
            if (cell.inspect > 0) {
              cell.inspectAvg = (cell.inspectVal / cell.inspect).toFixed(2);
            } else {
              cell.inspectAvg = 0;
            }
          }
        }
        tableData.push(cell);
      }
      return tableData;
    },
    isInterested(name) {
      for (let i = 0; i < this.$store.state.clientData.clientList.length; i++) {
        if (this.$store.state.clientData.clientList[i].name == name) {
          return this.$store.state.clientData.clientList[i].interest;
        }
      }
      return 0;
    },
    clearSelection() {
      this.$refs.mainTable.clearSelection();
    },
    handleSelectionChange(val) {
      let clientList = [];
      for (let i = 0; i < val.length; i++) {
        clientList.push(val[i].name);
      }
      this.multipleSelection = clientList;
      this.$emit("check", clientList);
    },
    update() {
      let clientsJSON = JSON.stringify(this.storedClients);
      let rangeJSON = JSON.stringify(this.storedRange);
      if (
        JSON.stringify(this.clients) != clientsJSON ||
        JSON.stringify(this.range) != rangeJSON
      ) {
        this.clients = JSON.parse(clientsJSON);
        this.range = JSON.parse(rangeJSON);
        this.tableData = this.fetchData();
        // console.log("summary table updated");
      }
    },
  },
  mounted() {
    this.update();
    let self = this;
    this.updateID = setInterval(() => {
      self.update();
    }, 200);
  },
  beforeDestroy() {
    clearInterval(this.updateID);
  },
};
</script>
